<?php
/**
 * ***********************************************************************************
 * 咨询鲤 PC端知识店铺-登录相关
 * 
 * @author Mr.RJH
 * @date 2025-09-17
 * @email<15213026209@163.com>
 * ***********************************************************************************
 */
namespace app\controller;

use app\BaseController;

use think\facade\Cache;
use think\captcha\facade\Captcha;
use think\facade\Log;
use think\facade\Session;
use think\exception\ValidateException;

use app\model\sms\TextMessageContentTemplateModel;
use app\model\sms\ZxlSmsVerifyCodeModel;

use app\model\user\ZxlTalentUserModel;

use app\service\SendSmsService;
use jwt\JwtHelper;

class Login extends BaseController
{

    /**
     * 发送短信验证码
     * 
     * @return string
     */
    public function send_verify_code()
    {
        if ($this->request->isPost()) {
            try {
                $post = $this->request->post();
                // 获取商户短信验证码签名
                $template_id = TextMessageContentTemplateModel::where(['store_id' => $this->request->m_id, 'platform_type' => 2, 'type' => 1, 'is_verify_code' => 1])->value('template_id');
                if (!$template_id) {
                    return json(['code' => 0, 'msg' => '商户暂未开通短信验证']);
                }
                if (!Captcha::check($post['captcha'])) {
                    return json(['code' => 1, 'msg' => '图形验证码错误']);
                }
                
                $sendSmsService = new SendSmsService($this->request->m_id);

                $result = $sendSmsService->send_sms_verify_code($post['mobile'], $template_id);
                if ($result) {
                    return json(['code' => 0, 'msg' => '验证码已发送']);
                } else {
                    return json(['code' => 1, 'msg' => '验证码发送失败']);
                }
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            } 
        }
    }

    /**
     * 短信验证码登录
     * 
     * @return json
     * @throws \Exception
     */
    public function sms_login()
    {
        if ($this->request->isPost()) {
            try {
                $post = $this->request->post();
                
                $m_id = $this->request->m_id;
                $verify_code_log = ZxlSmsVerifyCodeModel::where(['mobile' => $post['mobile']])->order('create_time', 'desc')->find();
                if ($verify_code_log['code'] != $post['verify_code']) {
                    return json(['code' => 1, 'msg' => '短信验证码错误，请重新输入']);
                }
                if (time() > $verify_code_log['expire_time']) {
                    return json(['code' => 1, 'msg' => '短信验证码已过期，请重新获取']);
                }
                unset($post['verify_code']);
                if (!isset($post['agree'])) {
                    return json(['code' => 1, 'msg' => '请勾选协议']);
                }
                $user = ZxlTalentUserModel::where(['m_id' => $m_id, 'mark' => 2, 'mobile' => $post['mobile']])->find();
                if (!$user) {
                    $user = new ZxlTalentUserModel();
                    $nickname = get_nickname();
                    $user->m_id = $m_id;
                    $user->nickname = base64_encode($nickname);
                    $user->nickname_two = preg_replace('/[\xf0-\xf7].{3}/', '', $nickname);
                    $user->avatar = 'https://api.youliyouhuo.com/img/background/icon77.png';
                    $user->mobile = $post['mobile'];
                    
                    $user->create_time = time();
                    $user->save();
                }
                // 生成token
                $channel = 'know_store';
                $user_table = 'know_store';
                $token = JwtHelper::signToken($user->id, $channel, $user_table);

                $user = $user->toArray();
                $user['token'] = $token;

                session('user', $user);
                
                return json(['code' => 0, 'msg' => '登录成功']);
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            } 
        }
    }

    /**
     * 密码登录
     * 
     * @return string
     * @throws \Exception
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            
            $m_id = $this->request->m_id;
            if (!isset($post['agree'])) {
                return json(['code' => 1, 'msg' => '请勾选协议']);
            }
            $user = ZxlTalentUserModel::where(['m_id' => $m_id, 'mark' => 2, 'mobile' => $post['mobile']])->find();
            if (!Captcha::check($post['captcha'])) {
                return json(['code' => 1, 'msg' => '图形验证码错误']);
            }
            if (empty($user)) {
                return json(['code' => 1, 'msg' => '用户不存在']);
            }
            if (md5(md5($post['password'])) != $user['password']) {
                return json(['code' => 1, 'msg' => '密码输入有误']);
            }
            if ($user['status'] == 0) {
                return json(['code' => 1, 'msg' => '账号已被禁用']);
            }
            // 生成token
            $channel = 'know_store';
            $user_table = 'know_store';
            $token = JwtHelper::signToken(['id' => $user->id, 'channel' => $channel, 'user_table' => $user_table]);

            $user = $user->toArray();
            $user['token'] = $token;
            
            unset($user['password']);
            session('user', $user);
            return json(['code' => 0, 'msg' => '登录成功']);
        }
        return $this->fetch();
    }

    /**
     * 退出登录
     * 
     * @return json
     */
    public function login_out()
    {
        Session::clear();
        return json(['code' => 0, 'msg' => '退出登录成功']);
    }

    /**
     * 图形验证码
     * 
     * @return \think\Response
     */
    public function captcha()
    {
        ob_clean();
        return Captcha::create();
    }

    /**
     * 登录协议
     * 
     * @return mixed
     */
    public function agreement()
    {
        $type = $this->request->param('type');

        $this->assign('type', $type);
        return $this->fetch();
    }
}